package com.carlyang.studentinfo.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

/**
 * 
 * @author carlyang
 *
 */
public class DBUtil {
	public static final String TAG = "DBUtil";
	// 数据库地址 localhost 或 具体IP地址,root用户只能用localhost登录，自定义用户carlyang才可以用IP地址登录。
	private static final String dbUrl = "jdbc:mysql://10.6.208.85:3306/db_studentinfo?useUnicode=true&characterEncoding=utf-8&useSSL=false";
	private static final String dbUrl2 = "jdbc:mysql://localhost:3306/db_studentinfo?useUnicode=true&characterEncoding=utf-8&useSSL=false";
	// 用户名
	private static final String dbUserName = "carlyang";
	// 密码
	private static final String dbPassword = "yangdong";
	// 驱动名称
	private static final String jdbcName = "com.mysql.jdbc.Driver";

	public DBUtil() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 使用用户指定的数据库参数，获取数据库连接
	 * 
	 * @param dbUrl
	 * @param dbUserName
	 * @param dbPassword
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection(String dbUrl, String dbUserName, String dbPassword) throws Exception {
		Class.forName(jdbcName);// 可以不需要
		Connection con = null;
		try {
			con = DriverManager.getConnection(dbUrl2, dbUserName, dbPassword);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
		}
		//System.out.println("getConnection over!");
		LogUtil.i(TAG, "getConnection OK");
		return con;
	}

	/**
	 * 使用默认参数获取数据库连接
	 * 如果数据库url有误，会导致DriverManager.getConnection执行5s后才有结果
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() throws Exception {
		Class.forName(jdbcName);// 可以不需要
		Connection con = null;
		try {
			//System.out.println("getConnection 1");
			con = DriverManager.getConnection(dbUrl2, dbUserName, dbPassword);
			//System.out.println("getConnection 2");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			//System.out.println("getConnection 3");
			con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
		}
		//System.out.println("getConnection over!");
		LogUtil.i(TAG, "getConnection OK");
		return con;
	}

	/**
	 * 关闭连接
	 * 
	 * @param stmt
	 * @param con
	 * @throws Exception
	 */
	public static void closeCon(Statement stmt, Connection con) throws Exception {
		if (stmt != null) {
			stmt.close();
			if (con != null) {
				con.close();
			}
		}
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @param con
	 * @throws Exception
	 */
	public static void closeCon(Connection con) throws Exception {
		if (con != null) {
			con.close();
		}
	}

	/**
	 * 数据库链接测试
	 * @param args
	 */
	public static void main(String[] args) {
		//DBUtil dbUtil = new DBUtil();
		try {
			DBUtil.getConnection();
			LogUtil.i(TAG, "数据库连接成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LogUtil.i(TAG, "数据库连接失败");
		}
	}

}
